import java.util.PriorityQueue;
import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;

public class Timer {
    // 通过PriorityBlockingQueue来组织任务
    private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue();
    //创建一个锁对象
    private Object mailBox = new Object();
     private Runnable runnable;
    // 构造方法，直接启动worker线程
    public Timer() {
        // 创建worker线程对象
        Worker worker = new Worker();
        // 启动线程
        worker.start();
    }


    // 执行计划，通过这个方法添加定时任务
    public void schedule(Runnable runnable, long time) {
        Task task = new Task(runnable, time);
        queue.offer(task);
        // 每增加一个任务就唤醒一次worker看有没有要执行的任务
        synchronized (mailBox) {
            mailBox.notifyAll();
        }
    }

     public static void main(String[] args) {
         Timer timer = new Timer();
         Runnable runnable = new Runnable() {
             @Override
             public void run() {
                 System.out.println("时间到了，我开始执行...");
             }
         };
         timer.schedule(runnable, 1000);

     }

    // 能过work完成对线程
    class Worker extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    // 获取距当前时间最短的任务
                    Task task = queue.take();
                    // 获取当前时间
                    long curr = System.currentTimeMillis();
                    if (curr >= task.getTime()) {
                        task.run();
                    } else {
                        // 时间没有到put回队列
                        queue.put(task);
                        // 最小等待时间
                        long waitTime = task.getTime() - curr;
                        synchronized (mailBox) {
                            mailBox.wait(waitTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


